package com.sensorfriendly.ui;

import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sensorfriendly.AppConstants;
import com.sensorfriendly.AppContext;
import com.sensorfriendly.R;
import com.sensorfriendly.model.Message;


/**
 * adapter for hosting messages
 *
 */
public class MessageListAdapter extends BaseAdapter {

	private Activity activity;
	private List<Message> data;
	private String category;
	private static LayoutInflater inflater=null;

	public MessageListAdapter(Activity a, String c, List<com.sensorfriendly.model.Message> d){		
        activity = a;
        category = c;
        data = d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

	public MessageListAdapter(Activity a, List<com.sensorfriendly.model.Message> d){		
        activity = a;
        data = d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return data.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }
    
    @SuppressLint("ShowToast")
	public View getView(final int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView==null)
            vi = inflater.inflate(R.layout.list_row, null);

        TextView msgTitle = (TextView)vi.findViewById(R.id.list_item_title);
        ImageView icon = (ImageView) vi.findViewById(R.id.scenario_icon);
        icon.setVisibility(View.GONE);
        final Message msg = data.get(position);    
        
        // Setting all values in listview
        msgTitle.setText(msg.toString());
        
        /****************************************
         * Handling for the Delete Button
         ****************************************/
        Button delete_button= (Button)vi.findViewById(R.id.delete_button);
        delete_button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				// Alert Dialog to confirm if the scenario should
				// be deleted or not
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
				
				// set title
				alertDialogBuilder.setTitle("ALERT : Delete Message?");

				alertDialogBuilder.setMessage("Are you sure you want to delete the Message : " + msg.toString());
				alertDialogBuilder.setCancelable(false);
				
				alertDialogBuilder.setPositiveButton("Delete",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						// Delete the Scenario
						final AppContext app = (AppContext) activity.getApplication();
						app.deleteMessages(msg);
						
						// Update the list in case of a change
						List<Message> messages = app.getScenarioMessages(category);
						MessageListAdapter.this.setMessages(messages);
						MessageListAdapter.this.notifyDataSetChanged();
					}
				});
				
				alertDialogBuilder.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						// if this button is clicked, just close
						// the dialog box and do nothing
						dialog.cancel();
					}
				});
				
				// create alert dialog
				AlertDialog alertDialog = alertDialogBuilder.create();
 
				// show it
				alertDialog.show();
			}
		});
        
        /****************************************
         * Handling for the Edit Button
         ****************************************/
        Button edit_button= (Button)vi.findViewById(R.id.edit_button);
        edit_button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				AppContext app = (AppContext) activity.getApplication();
				
				// if the device does not support microphone we only give user a dialog box to modify message content
				if(! app.isMicSupport()){
					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
	
					alertDialogBuilder.setTitle("Edit Message Name");
					//alertDialogBuilder.setMessage("Please enter the Message Name");
	
					// Set an EditText view to get user input 
					final EditText newMsg = new EditText(activity);
					newMsg.setSingleLine();
					newMsg.setText(msg.getMessageContent());
					alertDialogBuilder.setView(newMsg);
	
					alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							String value = newMsg.getText().toString();
							
							// Edit the Scenario Name if the current name 
							// has been changed and is not empty
							if(!msg.toString().equalsIgnoreCase(value)
								&& 
								!value.trim().matches("")){
								final AppContext app = (AppContext) activity.getApplication();
								
								Message newMessage = new Message();
								newMessage.setMessageContent(value);
								newMessage.setAudioFile(msg.getAudioFile());
								newMessage.setScenarioName(msg.getScenarioName());
								newMessage.setMessageImagePath(msg.getMessageImagePath());
								app.editMessage(msg.getMessageContent(), newMessage);
								
								// Update the list in case of a change
								MessageListAdapter.this.notifyDataSetChanged();							
							}
						}
					});
	
					alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					  public void onClick(DialogInterface dialog, int whichButton) {
					    // Canceled.
					  }
					});
					alertDialogBuilder.show();
				}
				// if the device has microphone show user the complete message editting dialog
				else{
					Intent intent = new Intent(activity, EditMessageDialog.class);
					intent.putExtra(AppConstants.MESSAGE, data.get(position).getMessageContent());
					intent.putExtra(AppConstants.CATEGORY, category);
					activity.startActivity(intent);
				}
			}
		});

        return vi;
    }
    public void setMessages(List<Message> messages){
    	this.data = messages;
    }
}